import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const modules: Record<string, any> = import.meta.glob("./modules/*.ts", { eager: true });
const routes: RouteRecordRaw[] = [];

Object.keys(modules).forEach((key) => {
  if (Array.isArray(modules[key].default)) {
    modules[key].default.forEach((item: any) => {
      routes.push(item);
    });
  } else if (typeof modules[key].default === "object") {
    routes.push(modules[key].default);
  }
});

const router = createRouter({
  history: createWebHistory(),
  routes,
});
router.beforeEach((to, from, next) => {
  NProgress.start();
  const token = localStorage.getItem("token");
  if (to.path !== "/login" && !token) {
    // 没登录
    next("/login");
    return;
  } else if (to.path === "/login" && token) {
    // 已经登录还去登录页
    next("/");
    return;
  }
  // TODO: 路由鉴权
  next();
});
router.afterEach(() => {
  NProgress.done();
});

export default router;
